/**
 * Copyright 2011 Joe Choi, All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package taobe.tec.reslite;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Joe Choi
 */
public class Resource {
	public Resource(String pathToDB) {
		connectURL = "jdbc:sqlite:" + pathToDB;
	}
	
	public void create(String name) throws SQLException, ClassNotFoundException {
		Class.forName("org.sqlite.JDBC");
		Connection conn = DriverManager.getConnection(connectURL);
		Statement stm = conn.createStatement();
		createResourceTable(stm);
		createResource(stm, name);
		stm.close();
		conn.close();
	}
	
	public List<String> list() throws ClassNotFoundException, SQLException {
		List<String> l = new ArrayList<String>();
		Class.forName("org.sqlite.JDBC");
		Connection conn = DriverManager.getConnection(connectURL);
		Statement stm = conn.createStatement();
		
		String sql = "select res_name from resm_resource";
		ResultSet rset= stm.executeQuery(sql);
		//rset.beforeFirst();
		while(rset.next()) {
			l.add(rset.getString("res_name"));
		}
		
		stm.close();
		conn.close();
		
		return(l);
	}
	
	private void createResourceTable(Statement stm) throws SQLException {
		String sql = "CREATE TABLE IF NOT EXISTS resm_resource (" +
					 "res_name TEXT PRIMARY KEY NOT NULL" +
					 ")";
		stm.execute(sql);
	}
	
	private void createResource(Statement stm, String name) throws SQLException {
		String sql = "insert into resm_resource(res_name) values('?')";
		sql = sql.replace("?", name);
		stm.execute(sql);
	}
		
	private String connectURL;
}
